package com.huatai.exchange.deal;

import com.faneui.common.exception.BusinessException;
import com.faneui.common.utils.CloseUtils;
import com.faneui.integration.http.HttpClientUtils;
import com.google.common.collect.Maps;
import com.huatai.exchange.dal.model.ExcDataFileInfo;
import com.huatai.exchange.facade.Contents;
import com.huatai.exchange.facade.FileSourceConstants;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Map;
import java.util.UUID;

@Service("fileCreateHttpDealService")
public class FileCreateHttpDealServiceImpl extends AbstractFileCreateDealServiceImpl implements FileCreateDealService {

    void generate(Map<String, Object> valueMap, ExcDataFileInfo dataFileInfo, StringBuffer fileNames, StringBuffer filePaths) throws BusinessException {
        String tmpFilePath = tmpFile + UUID.randomUUID().toString();
        File f = new File(tmpFilePath);
        OutputStream os = null;
        try {
            String fileName = formatStr(dataFileInfo.getFileName(), valueMap);
            String httpUrl = formatStr((String) valueMap.get(FileSourceConstants.HTTP_URL), valueMap);

            os = new FileOutputStream(f);
            // 下载文件的后缀
            String fileSuffix = fileName.substring(fileName.lastIndexOf(".") + 1);
            HttpClientUtils.downLoadFile(httpUrl, Maps.newHashMap(), os, fileSuffix);
            fileNames.append(",").append(fileName);
            String filePath = fileOperateService.uploadFile(f);
            filePaths.append(",").append(filePath);
            valueMap.put(Contents.FILE_GC, valueMap.get(Contents.FILE_GC) + "," + filePath);
        } catch (Exception ex) {
            BusinessException.throwBusinessException(ex);
        } finally {
            CloseUtils.safeClose(os);
            f.deleteOnExit();
        }
    }

    public static void main(String[] args) {
        String fileName = "f.ane.xlsx";
        String fileSuffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        System.out.println(fileSuffix);
    }
}
